package com.youkeyi.ddy.cloud.gateway.swagger;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

/**
 * SwaggerHeaderFilter
 *
 * @Author liuxiawang
 * @Date 2021-03-09 23:42
 * @Location shenzhen.china
 */
@Component
@Slf4j
public class SwaggerHeaderFilter extends AbstractGatewayFilterFactory {
    private static final String HEADER_NAME = "X-Forwarded-Prefix";

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getURI().getPath();
            if (!StringUtils.endsWithIgnoreCase(path, SwaggerProvider.API_URI)) {
                return chain.filter(exchange);
            }
            ServerHttpRequest newRequest = request.mutate().path(SwaggerProvider.API_URI).build();
            // String basePath = path.substring(0, path.lastIndexOf(SwaggerProvider.API_URI));
            // ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME, basePath).path(SwaggerProvider.API_URI).build();
            ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
            return chain.filter(newExchange);

        };
    }
}
